package routers

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

//定义路由切片
var options []func(*gin.Engine)

// Include 注册路由切片
func Include(opts ...func(*gin.Engine)) {
	options = append(options, opts...)
}

// Init 初始化注册路由
func Init() *gin.Engine {
	r := gin.Default()
	//定义跨域通过 (临时放行)
	r.Use(Cors())
	//定义一些验证规则
	r.Use(AuthRequired())
	for _, v := range options {
		v(r)
	}
	return r
}

// Cors 定义跨域问题
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method

		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		// 处理请求
		c.Next()
	}
}

// AuthRequired 定义安全认证
func AuthRequired() gin.HandlerFunc {
	return func(context *gin.Context) {
		context.Next()
	}
}
